/*
剑指 Offer 29. 顺时针打印矩阵
解题思路：模拟
 */
public class Offer29 {
  public static void main(String[] args) {
    int[][] num = new int[][]{
            {1,2,3},
            {4,5,6},
            {7,8,9}
    };
  }

  public int[] spiralOrder(int[][] matrix) {
    if (matrix.length == 0) return new int[0];
    int[] res = new int[matrix.length * matrix[0].length];
    int up = 0;
    int down = matrix.length - 1;
    int left = 0;
    int right = matrix[0].length - 1;
    int index = 0;
    while (true){
      for (int i = left;i <= right;i++){
        res[index++] = matrix[up][i];
      }
      if (++up > down){
        break;
      }
      for (int i = up; i <= down; i++) {
        res[index++] = matrix[i][right];
      }
      if (--right < left) {
        break;
      }
      for (int i = right; i >= left; i--) {
        res[index++] = matrix[down][i];
      }
      if (--down < up) {
        break;
      }
      for (int i = down; i >= up; i--) {
        res[index++] = matrix[i][left];
      }
      if (++left > right) {
        break;
      }
    }
    return res;
  }
}
